import { IsNotNullOrUndefined } from "@lib/helper";
import dayjs from "dayjs";
import type { ResolvedChildren, ResolvedJSXElement } from "solid-js";
import type { TableColumnProps } from "./types";

export const SubTotal = <T = {},>(datas: T[], name: string) => {
  const total = datas.reduce((p, data: any) => {
    if (data !== undefined && data !== null) {
      const value = data[name];

      if (value !== undefined && data !== null) {
        if (typeof value === "number") {
          p += value;
        } else {
          try {
            const numberValue = parseInt(value);
            p += numberValue;
          } catch {}
        }
      }
    }

    return p;
  }, 0);

  return total;
};

export const getValue = <T extends { [key: string]: any }>(
  data: T,
  name: string
) => {
  return data[name];
};

export const formatDate = (
  format?: string
): TableColumnProps<any>["children"] => {
  return (data, column, index) => {
    if (!IsNotNullOrUndefined(column.name)) {
      return "";
    }

    const value = getValue(data, column.name!);

    if (!IsNotNullOrUndefined(value)) {
      return "";
    }

    try {
      return dayjs(value).format(format ?? "YYYY-MM-DD HH:mm:ss");
    } catch {
      return value;
    }
  };
};

export const hasNumberWidth = <T = {},>(col: TableColumnProps<T>) => {
  return col.width !== undefined && typeof col.width === "number";
};

export const wrappedStickyStyle = <T = {},>(
  column: TableColumnProps<T>,
  d: { left: number; right: number }
) => {
  column.style = column.style ?? {};

  // 固定列宽
  if (column.width !== undefined) {
    if (typeof column.width === "number") {
      column.style["width"] = `${column.width}px`;
    } else {
      column.style["width"] = column.width;
    }
  }

  // 固定列的粘性间距
  if (hasNumberWidth(column) && column.fixed !== undefined) {
    column.style["min-width"] = `${column.width}px`;
    column.style["max-width"] = `${column.width}px`;
    column.style[column.fixed] = `${d[column.fixed] - (column.width as number)
      }px`;
  }

  // return column.style;
};


export const IsResolvedJSXElementArray = (
  value: ResolvedChildren
): value is ResolvedJSXElement[] => {
  return true;
};